import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:my_app_01/config.dart';
import 'package:my_app_01/model/User.dart';
import 'package:my_app_01/pages/auth/components/input.dart';
import 'package:my_app_01/service/HttpUtils.dart';
import 'package:my_app_01/utils/auth.dart';

class LoginPage extends StatefulWidget {
  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  var imageKey = "";
  var imageUrl = "";

  var loginInfo = {
    "account": "km01",
    "password": "8520000000",
    "verCode": "",
    "verKey": ""
  };

  final _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    getCheckcodeImage();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        image: DecorationImage(
            fit: BoxFit.cover,
            image: NetworkImage("https://meal.kmszzxt.cn/mp/images/admin.png")),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: Container(
          padding: const EdgeInsets.only(left: 40, right: 40),
          child: Form(
            key: _formKey,
            child: ListView(
              children: [
                const Center(
                  child: SizedBox(
                    height: 60,
                    child: Image(
                      image: NetworkImage(
                          "https://meal.kmszzxt.cn/mp/images/logo.png"),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 20),
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: const Text(
                      "管理者登录",
                      style: TextStyle(
                          color: Colors.teal,
                          fontSize: 32,
                          fontWeight: FontWeight.w600),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 10),
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: const Text(
                      "欢迎登录学生营养餐与卫生健康综合管理平台",
                      style: TextStyle(color: Colors.teal, fontSize: 16),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 24),
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: LoginInput(
                        label: "用户名",
                        hintText: "请输入用户名",
                        icon: Icons.person,
                        initialValue: loginInfo['account'],
                        saveFunc: (value) {
                          setState(() {
                            loginInfo['account'] = value;
                          });
                        },
                        validatorFunc: (String? value) {
                          return value != null && value.length > 1
                              ? null
                              : "请输入用户名";
                        }),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 24),
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: LoginInput(
                        label: "密码",
                        hintText: "请输入密码",
                        icon: Icons.lock,
                        keyboardType: TextInputType.visiblePassword,
                        obscureText: true,
                        initialValue: loginInfo['password'],
                        saveFunc: (value) {
                          setState(() {
                            loginInfo['password'] = value;
                          });
                        },
                        validatorFunc: (String? value) {
                          return value != null && value.length > 5
                              ? null
                              : "密码最少五个字符";
                        }),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 24),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Expanded(
                        flex: 2,
                        child: TextFormField(
                          decoration: const InputDecoration(
                            labelText: "验证码",
                            hintText: "请输入验证码",
                            prefixIcon: Icon(Icons.lock),
                            contentPadding: EdgeInsets.all(15),
                            border: OutlineInputBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8)),
                              borderSide:
                                  BorderSide(color: Colors.black12, width: 1),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8)),
                              borderSide:
                                  BorderSide(color: Colors.black12, width: 1),
                            ),
                          ),
                          onSaved: (value) {
                            setState(() {
                              loginInfo['verCode'] = value!;
                            });
                          },
                          validator: (String? value) {
                            return value != null && value.length != 0
                                ? null
                                : "请输入验证码";
                          },
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: InkWell(
                          onTap: () {
                            getCheckcodeImage();
                          },
                          child: Container(
                            margin: const EdgeInsets.only(left: 10),
                            padding: const EdgeInsets.only(left: 10, right: 10),
                            decoration: const BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8)),
                              border: Border(
                                top:
                                    BorderSide(color: Colors.black12, width: 1),
                                bottom:
                                    BorderSide(color: Colors.black12, width: 1),
                                right:
                                    BorderSide(color: Colors.black12, width: 1),
                                left:
                                    BorderSide(color: Colors.black12, width: 1),
                              ),
                            ),
                            child: getImage(imageUrl),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  width: double.infinity,
                  height: 70,
                  padding: const EdgeInsets.only(top: 24),
                  child: ElevatedButton(
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all(
                        const RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(Radius.circular(8)),
                        ),
                      ),
                      foregroundColor: MaterialStateProperty.all(Colors.white),
                      backgroundColor: MaterialStateProperty.all(Colors.teal),
                    ),
                    onPressed: () {
                      doLogin(context);
                    },
                    child: const Text(
                      '登 录',
                      style: TextStyle(fontSize: 18),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  dynamic doLogin(context) async {
    if (_formKey.currentState != null) {
      if (_formKey.currentState!.validate()) {
        _formKey.currentState!.save();
        EasyLoading.show(status: '登录中...');
        var response = await HttpUtils.post(
            "${MyConfig.baseUrl}/auth-api/auth/login/accountLogin",
            data: loginInfo);
        if (response['status'] == 0) {
          LoginPrefs.saveUserInfo(UserModel.fromJson(response['data']['userInfo']));
          LoginPrefs.saveToken(response['data']['token']);

          EasyLoading.showSuccess('登录成功!');
          Future.delayed(const Duration(milliseconds: 500), () {
            EasyLoading.dismiss();
            Navigator.pushNamedAndRemoveUntil(
                context, '/home', (route) => false);
          });
        } else if (response['status'] == 1) {
          EasyLoading.showSuccess('登录失败!');
        }
      }
    }
    return true;
  }

  /// 获取图片验证码
  void getCheckcodeImage() async {
    var response = await HttpUtils.post(
        "${MyConfig.baseUrl}/auth-api/auth/captcha/generateAccountLoginImageCaptcha");
    setState(() {
      if (response['data'] != null) {
        loginInfo['verKey'] = response['data']['key'];
        imageUrl = response['data']['image'];
      }
    });
  }

  /// 渲染base64图片方法
  Widget getImage(String s, [double width = 100, double height = 52]) {
    var code = s.split(',').last;
    Uint8List imageBytes = const Base64Decoder().convert(code);
    return Container(
      child: Image.memory(imageBytes, height: height, width: width,
          errorBuilder: (context, error, stackTrace) {
        return Image.asset(
          "images/failed.png",
          height: height,
          width: width,
        );
      }),
    );
  }
}
